package com.xxx.springboot.distributedsession;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 分布式session filter
 */
@Slf4j
@Component
//@WebFilter(filterName = "distributedSessionFilter", urlPatterns = "*", initParams = {@WebInitParam(name = "sessionIdCookieName", value="session_id"), @WebInitParam(name = "maxInactiveInterval", value="1800")})
@WebFilter(filterName = "distributedSessionFilter", urlPatterns = "*")
public class DistributedSessionFilter implements Filter {

    private FilterConfig filterConfig;
    private String sessionIdCookieName = "sessionIdCookieName";
    private int maxInactiveInterval = 1800;
    private String cookieDomain = null;
    private String cookieContextPath = null;

    @Override
    public void init(FilterConfig filterConfig) {
    	log.info("DistributedSessionFilter init......");
        this.filterConfig = filterConfig;
//        String sessionIdCookieNameStr = filterConfig.getInitParameter("sessionIdCookieName");
//        this.sessionIdCookieName = sessionIdCookieNameStr;
//        String maxInactiveIntervalStr = filterConfig.getInitParameter("maxInactiveInterval");
//        this.maxInactiveInterval = Integer.parseInt(maxInactiveIntervalStr);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        DistributedHttpRequest distributedHttpRequest = new DistributedHttpRequest(httpRequest, httpResponse, filterConfig.getServletContext());
        distributedHttpRequest.setSessionIdCookieName(sessionIdCookieName);
        distributedHttpRequest.setMaxInactiveInterval(maxInactiveInterval);
        distributedHttpRequest.setCookieDomain(cookieDomain);
        distributedHttpRequest.setCookieContextPath(cookieContextPath);

        chain.doFilter(distributedHttpRequest, httpResponse);

        DistributedHttpSession session = distributedHttpRequest.currentSession();
        if (null != session) {
            //同步cache
            if (!session.synchronizationCache()) {
                //session已失效，删除cookie
                CookieUtil.invalidCookie(httpRequest, httpResponse, sessionIdCookieName, cookieDomain, cookieContextPath);
            }
        }
    }

    @Override
    public void destroy() {
        //do nothing
    }
}
